package dao.impl;

import dao.IUserDao;
import entities.User;

public class UserDao extends CommonDao<User> implements IUserDao {

	public User find(int id) {
		try {
			return em.find(User.class, id);
		} catch (Exception e) {
			return null;
		}
	}
	
	
	public User find(String login) {
		try {
			return (User) em
					.createQuery(
							"select u from User u where u.login='"
									+ login + "'").getSingleResult();
		} catch (javax.persistence.NoResultException e) {
			return null;
		}
	}

	@Override
	public String getWhereClause(User obj) {
		StringBuilder clause = new StringBuilder();
		clause.append(" ");
		if (obj.getId() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("id = ").append(" obj.getId").append(" ");
			}
		}
		if (obj.getVersion() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("version = ").append(" obj.getVersion")
						.append(" ");
			}
		}
		if (obj.getFisrtName() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("fisrtName = ").append(" obj.getFisrtName")
						.append(" ");
			}
		}
		if (obj.getLastName() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("lastName = ").append(" obj.getLastName")
						.append(" ");
			}
		}
		if (obj.getLogin() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("login = ").append(" obj.getLogin").append(" ");
			}
		}
		if (obj.getPassword() != null) {
			if (clause.length() > 1) {
				clause.append(" and");
				clause.append("password = ").append(" obj.getPassword")
						.append(" ");
			}
		}
		return clause.toString();
	}

}